import React, {Component} from 'react';
import {Table, Button, message, Modal, Input} from 'antd';
import Ajax from '../../util/AjaxUtil';
import './Department.less';
import qs from 'qs';

class Department extends Component {

    constructor(props) {
        super(props);

        this.state = {
            departmentData: [],
            departmentLoading: false,
            expandedRowKeys: [],
            addDepartmentModalVisible: false,
            addDepartmentModalName: null,
            editDepartmentModalVisible: false,
            editDepartmentModalName: null,
            clickRow: null
        };

    }

    render() {
        const columns = [{
            title: '部门名称',
            dataIndex: 'name',
            key: 'name',
        }, {
            title: '操作',
            dataIndex: 'id',
            key: 'id',
            width: 300,
            render: (text, record, index) => {
                return (<div className={"actionDiv"}>
                    <Button type="primary" onClick={this.openAddDepartmentModal.bind(this, record)}>添加</Button>
                    {text > 1 ? <Button type="primary" onClick={this.openEditDepartmentModal.bind(this, record)}>修改</Button> : null}
                    {text > 1 ? <Button type="danger" onClick={this.deleteDepartment.bind(this, record)}>删除</Button> : null}
                </div>);

            }
        }];

        let instance = this;

        return (
            <div>
                <Table loading={this.state.departmentLoading}
                       size={'small'}
                       pagination={false}
                       rowKey={(record) => {
                           return record.id
                       }}
                       dataSource={this.state.departmentData}
                       defaultExpandAllRows={true}
                       expandedRowKeys={this.state.expandedRowKeys}
                       columns={columns}
                       rowClassName={'departmentRow'}
                       onExpand={(expanded, record) => {
                           let expandedRowKeys = [...instance.state.expandedRowKeys];
                           if (expanded) {
                               expandedRowKeys.push(record.id);
                           } else {
                               let index = -1;
                               while ((index = expandedRowKeys.findIndex(key => key === record.id)) !== -1) {
                                   expandedRowKeys.splice(index, 1);
                               }
                           }
                           instance.setState({expandedRowKeys: expandedRowKeys});
                       }}
                />
                <Modal
                    title={"添加子部门"}
                    visible={this.state.addDepartmentModalVisible}
                    cancelText={"取消"}
                    okText={"确定"}
                    onCancel={() => {
                        instance.setState({
                            addDepartmentModalVisible: false,
                            addDepartmentModalName: null
                        });
                    }}
                    onOk={this.addDepartment.bind(this)}
                >
                    部门名称:
                    <Input value={this.state.addDepartmentModalName}
                           type={"text"}
                           maxLength={10}
                           onChange={e => {
                               instance.setState({
                                   addDepartmentModalName: e.target.value
                               });
                           }}
                    />
                </Modal>

                <Modal
                    title={"修改部门"}
                    visible={this.state.editDepartmentModalVisible}
                    cancelText={"取消"}
                    okText={"修改"}
                    onCancel={() => {
                        instance.setState({
                            editDepartmentModalVisible: false
                        });
                    }}
                    onOk={this.editDepartment.bind(this)}
                >
                    部门名称:
                    <Input value={this.state.editDepartmentModalName}
                           type={"text"}
                           maxLength={10}
                           onChange={e => {
                               instance.setState({
                                   editDepartmentModalName: e.target.value
                               });
                           }}
                    />
                </Modal>
            </div>
        );
    }

    componentDidMount() {
        let instance = this;

        this.setState({
            departmentLoading: true
        });
        Ajax.post("/userCenter/department/findAllDepartmentTree")
            .then((response) => {
                let data = [];
                let expandedRowKeys = [];
                data.push(response.data);
                instance.findExpandedRowKeys(response.data, expandedRowKeys);
                instance.setState({
                    departmentData: data,
                    departmentLoading: false,
                    expandedRowKeys: expandedRowKeys
                });
            })
            .catch((error) => {
                message.error("获取数据失败");
            });
    }

    findExpandedRowKeys(data, expandedRowKeys) {
        if (data.children && data.children.length > 0) {
            expandedRowKeys.push(data.id);

            data.children.map((item, key, map) => {
                this.findExpandedRowKeys(item, expandedRowKeys);
                return item;
            });
        }
    }

    openAddDepartmentModal(record) {
        this.setState({
            addDepartmentModalVisible: true,
            clickRow: record
        });
    }

    addDepartment() {
        if (this.state.addDepartmentModalName === null
            || this.state.addDepartmentModalName.length === 0) {
            message.error("部门名称不能为空");
            return;
        }

        let instance = this;
        Ajax.post("/userCenter/department/addDepartment", qs.stringify({
            name: this.state.addDepartmentModalName,
            parentId: this.state.clickRow.id
        }))
            .then((response) => {
                if (response.data.result) {
                    message.success("添加成功");
                    instance.setState({
                        addDepartmentModalVisible: false,
                        addDepartmentModalName: null
                    });
                    instance.componentDidMount();
                } else {
                    message.error(response.data.message);
                }
            })
            .catch((error) => {
                message.error("添加失败")
            });
    }

    editDepartment() {
        if (this.state.editDepartmentModalName === null
            || this.state.editDepartmentModalName.length === 0) {
            message.error("部门名称不能为空");
            return;
        }

        let instance = this;
        Ajax.post("/userCenter/department/editDepartment", qs.stringify({
            name: this.state.editDepartmentModalName,
            id: this.state.clickRow.id
        }))
            .then((response) => {
                if (response.data.result) {
                    message.success("修改成功");
                    instance.setState({
                        editDepartmentModalVisible: false
                    });
                    instance.componentDidMount();
                } else {
                    message.error(response.data.message);
                }
            })
            .catch((error) => {
                message.error("修改失败")
            });
    }

    openEditDepartmentModal(record) {
        this.setState({
            editDepartmentModalVisible: true,
            clickRow: record,
            editDepartmentModalName: record.name
        });
    }

    deleteDepartment(record){
        let instance = this;
        Modal.confirm({
            cancelText:"取消",
            content:"是否删除部门"+record.name+"?",
            okText:"删除",
            onOk:(close)=>{
                Ajax.post("/userCenter/department/deleteDepartment", qs.stringify({
                    id: record.id
                }))
                    .then((response) => {
                        if (response.data.result) {
                            message.success("删除成功");
                            instance.componentDidMount();
                            close();
                        } else {
                            message.error(response.data.message);
                        }
                    })
                    .catch((error) => {
                        message.error("删除失败")
                    });
            }
        });
    }
}

export default Department;